package com.yaorange.api;

import com.alibaba.fastjson2.JSONObject;
import com.yaorange.common.constant.CacheConstants;
import com.yaorange.common.constant.Constants;
import com.yaorange.common.core.domain.AjaxResult;
import com.yaorange.common.core.domain.entity.SysUser;
import com.yaorange.common.core.domain.model.LoginUser;
import com.yaorange.common.core.redis.RedisCache;
import com.yaorange.common.enums.SmsEnum;
import com.yaorange.common.exception.ServiceException;
import com.yaorange.common.utils.SecurityUtils;
import com.yaorange.common.utils.nongjt.SmsUtils;
import com.yaorange.common.utils.nongjt.ValidateCodeUtils;
import com.yaorange.framework.web.service.SysLoginService;
import com.yaorange.framework.web.service.TokenService;
import com.yaorange.nongjt.domain.NjtLoginUser;
import com.yaorange.nongjt.domain.NjtUserPerfect;
import com.yaorange.nongjt.domain.NjtUserRegister;
import com.yaorange.nongjt.domain.Result;
import com.yaorange.nongjt.service.INjtSerialAuthService;
import com.yaorange.nongjt.service.INjtUserPerfectService;
import com.yaorange.nongjt.service.INjtUserRegisterService;
import com.yaorange.nongjt.vo.NjtUserLoginVO;
import com.yaorange.nongjt.vo.NjtUserRegisterVO;
import com.yaorange.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(value = "会员管理", tags = "会员管理")
@RestController
@RequestMapping("/api/user")
public class NjtUserAPI {

    @Autowired
    INjtSerialAuthService serialAuthService;
    @GetMapping("/querySerialAuthList")
    public Result querySerialAuthList(@RequestParam String mobilePhone) {
        return serialAuthService.querySerialAuthList(mobilePhone);
    }

    @Autowired
    private INjtUserRegisterService userRegisterService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private INjtUserPerfectService userPerfectService;

    @Autowired
    private TokenService tokenService;

    /**
     * 校验⼿机号是否可以被注册
     *
     * @param mobilePhone 注册⼿机号
     * @return
     */
    @ApiOperation("校验⼿机号是否可以被注册")
    @ApiImplicitParam(name = "mobilePhone", value = "注册⼿机号", required
            = true, dataType = "String")
    @GetMapping("/checkMobilePhone")
    public AjaxResult checkMobilePhone(@RequestParam("mobilePhone") String
                                               mobilePhone) {
        NjtUserRegister userRegister = userRegisterService.getByMobilePhone(mobilePhone);
        if (null != userRegister) {
            return AjaxResult.error("该⼿机号已被注册,请更换注册⼿机号");
        }
        return AjaxResult.success("⼿机号可⽤");
    }

    /**
     * 发送短信验证码
     *
     * @param mobilePhone ⼿机号
     * @return
     */
    @ApiOperation("发送短信验证码")
    @ApiImplicitParam(name = "mobilePhone", value = "⼿机号", required = true,
            dataType = "String")
    @GetMapping("/sendValidateCode")
    public AjaxResult sendValidateCode(@RequestParam("mobilePhone") String mobilePhone) {
        // ⽣成6位随机验证码
        String code = ValidateCodeUtils.generateValidateCode(6);
//        // 调⽤阿⾥云短信接⼝，给⽤户发送短信
//        JSONObject param = new JSONObject();
//        param.put("code", code);
//        Boolean result = SmsUtils.sendSms(mobilePhone, param, SmsEnum.REGISTER_TEMPLATE_CODE);
//        if (!result) {
//            log.info("短信发送接⼝，⼿机号，{}，验证码：{}，发送失败！", mobilePhone,
//                    code);
//            return AjaxResult.error("发送失败");
//        }
//        log.info("短信发送接⼝，⼿机号，{}，验证码：{}，发送成功！", mobilePhone, code);
        // 将验证码放⼊Redis 设置失效时间为5分钟
        redisCache.setCacheObject(CacheConstants.VALIDATE_PREFIX + mobilePhone, code, 5, TimeUnit.MINUTES);
        return AjaxResult.success("发送成功", code);
    }


    @Autowired
    private SysLoginService loginService;
    /**
     *会员登录
     *
     * @param loginVO 登录信息
     * @return 结果
     */
    @ApiOperation("会员登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody NjtUserLoginVO loginVO) {
        // ⽣成token
        String token = loginService.appLogin(loginVO.getUsername(), loginVO.getPassword());
        AjaxResult result = AjaxResult.success();
        result.put(Constants.TOKEN, token);
        return result;
    }

    /**
     * 会员注册
     *
     * @param registerVO
     * @return
     */
    @ApiOperation("会员注册")
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody NjtUserRegisterVO registerVO) {
        String mobilePhone = registerVO.getMobilePhone();
        String password = registerVO.getPassword();
        String checkCode = registerVO.getCheckCode();
        // ⽐对验证码是否⼀致
        String code = redisCache.getCacheObject(CacheConstants.VALIDATE_PREFIX
                + mobilePhone);
        if (!checkCode.equals(code)) {
            return AjaxResult.error("验证码有误");
        }
        // 保存注册信息
        return userRegisterService.saveRegister(mobilePhone, password);
    }

    /**
     * 获取当前登录⽤户信息
     *
     * @return
     */
    @ApiOperation("获取当前登录⽤户信息")
    @GetMapping("/queryLoginUser")
    public AjaxResult queryLoginUser() {
        // 当前登录系统⽤户
        LoginUser sysUser = SecurityUtils.getLoginUser();
        if (sysUser == null) {
            throw new ServiceException("当前登录信息查询失败");
        }
        // 查询最新的系统⽤户信息，避免前端更新⽤户信息后，未重新登录导致数据未刷新情况
        SysUser user = sysUserService.selectUserById(sysUser.getUserId());
        if (null != user) {
            sysUser.setUser(user);
        }
        NjtLoginUser loginUser = new NjtLoginUser();
        loginUser.setSysUser(sysUser);
        // 查询会员注册信息
        NjtUserRegister userRegister = userRegisterService.getByMobilePhone(sysUser.getUsername());
        if (null != userRegister) {
            loginUser.setUserRegister(userRegister);
            Long userId = userRegister.getId();
            // 查询会员完善信息
            NjtUserPerfect userPerfect = userPerfectService.getByRegisterUserId(userId);
            if (null != userPerfect) {
                loginUser.setUserPerfect(userPerfect);
            }
        }
        return AjaxResult.success(loginUser);
    }
    @ApiOperation("更新密码")
    @PostMapping("/forgotPassword")
    public AjaxResult updatePassword(@RequestBody NjtUserRegisterVO registerVO) {
        String mobilePhone = registerVO.getMobilePhone();
        String newPassword = registerVO.getPassword();
        String checkCode = registerVO.getCheckCode();

        // 验证验证码
        String code = redisCache.getCacheObject(CacheConstants.VALIDATE_PREFIX + mobilePhone);
        if (!checkCode.equals(code)) {
            return AjaxResult.error("验证码有误");
        }

        // 更新密码
        userRegisterService.updatePassword(mobilePhone, newPassword);

        return AjaxResult.success("密码更新成功");
    }

    /**
     * 刷新token
     *
     * @param request
     * @return
     */
    @ApiOperation("刷新token")
    @PostMapping("/refreshToken")
    public AjaxResult refreshToken(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        tokenService.refreshToken(loginUser);
        return AjaxResult.success("刷新成功");
    }
}
